package com.webfinal.backsystem.interceptor;

import com.alibaba.fastjson.JSONObject;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


@Component
@Aspect
public class HTTPAspect {
    private Logger LOG = LoggerFactory.getLogger(HTTPAspect.class);

    @Pointcut("execution(public * com.webfinal.backsystem.controller.*.*(..))")
    public void log(){}

    @Before("log()")
    public void doBefore(JoinPoint joinPoint){
        try {
            // http请求
            ServletRequestAttributes attributes=(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request=attributes.getRequest();
            // 获取http请求内容
            StringBuilder stringBuilder=new StringBuilder();
            stringBuilder.append("\n");
            stringBuilder.append("###################请求信息开始###################\n");
            stringBuilder.append("Controller:" ).append(joinPoint.getSignature().getDeclaringTypeName()).append("\n");
            stringBuilder.append("Method:" ).append(joinPoint.getSignature().getName()).append("\n");
            stringBuilder.append("HTTP Method:" ).append(request.getMethod()).append("\n");
            stringBuilder.append("Request Parameter:" ).append(JSONObject.toJSONString(joinPoint.getArgs())).append("\n");
            stringBuilder.append("URI:" ).append(request.getRequestURI()).append("\n");
            stringBuilder.append("ALL URI:" ).append(request.getRequestURL()).append("\n");
            stringBuilder.append("request IP:" ).append(request.getRemoteHost()).append("\n");
            stringBuilder.append("###################请求信息结束###################\n");
            LOG.info(stringBuilder.toString());
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    @AfterReturning(returning = "retObject", pointcut = "log()")
    public void doAfter(JoinPoint joinPoint, Object retObject) {
        try {
            StringBuilder stringBuilder=new StringBuilder();
            stringBuilder.append("\n");
            stringBuilder.append("###################返回信息开始###################\n");
            stringBuilder.append("Controller:" ).append(joinPoint.getSignature().getDeclaringTypeName()).append("\n");
            stringBuilder.append("Method:" ).append(joinPoint.getSignature().getName()).append("\n");
            stringBuilder.append("Response Parameter:" ).append(JSONObject.toJSONString(retObject)).append("\n");
            stringBuilder.append("###################返回信息结束###################\n");
            LOG.info(stringBuilder.toString());
        } catch (Exception e){
            e.printStackTrace();
        }
    }
}
